package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	uuid2 "github.com/google/uuid"
	"io"
	"log"
	"net/http"
)

type httpRequest struct {
	Method    string //请求方式
	DomainUrl string //域名
	Schema    string //协议
	Uri       string
}

func GetBaseRequest() *httpRequest {
	httpRequest := &httpRequest{
		Method:    "POST",
		DomainUrl: "127.0.0.1:8080",
		Schema:    "http",
	}
	return httpRequest
}

func GetLoginBody() *map[string]interface{} {
	userBody := make(map[string]interface{}, 0)
	userBody["username"] = "holina123"
	userBody["password"] = "123456"
	return &userBody
}

func main() {
	//获取基本的请求参数
	baseRequest := GetBaseRequest()
	baseRequest.Uri = "v1/login"

	//获取登录请求的字节body
	loginBody := GetLoginBody()
	loginBodyByte, _ := json.Marshal(loginBody)
	requestmap := make(map[string]interface{})
	err := json.Unmarshal(loginBodyByte, &requestmap)
	uuid, _ := uuid2.NewUUID()
	uuidstr := uuid.String()
	requestmap["RequestId"] = uuidstr
	//body, _ := json.Marshal(requestmap)
	//buffer := &bytes.Buffer{}
	//buffer.Write(body)
	buffer := new(bytes.Buffer)
	err = json.NewEncoder(buffer).Encode(requestmap)

	//创建http请求
	context.Background().Value(requestmap)
	url := baseRequest.Schema + "://" + baseRequest.DomainUrl + "/" + baseRequest.Uri + "?RequestId="+uuidstr
	request, err := http.NewRequestWithContext(context.Background(), baseRequest.Method, url, buffer)
	if err != nil {
		log.Fatalf("NewRequest fail msg：%v", err)
	}

	//设置请求头Header
	request.Header.Set("content-type", "application/json")
	request.Header.Set("Cache-Control","no-cache")

	resp, err := http.DefaultClient.Do(request)
	if err != nil {
		log.Fatalf("Send PostRequest failed, msg: %v", err)
	}
	respByte, err := io.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		log.Fatalf("Get respByte body failed, msg:%v", respByte)
	}
	respData := make(map[string]interface{}, 0)
	json.Unmarshal(respByte, &respData)
	fmt.Println(string(respByte))
	fmt.Println(respData)
}
